package cn.stylefeng.guns.core;

import cn.stylefeng.guns.config.AliSmsProperties;
import cn.stylefeng.guns.utils.Constant;
import cn.stylefeng.guns.utils.StringUtil;
import cn.stylefeng.guns.utils.redis.RedisCache;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@ConditionalOnProperty(prefix = "sms", name = "access-key-id")
public class SmsService {

    @Autowired
    private IAcsClient client;

    @Autowired
    private AliSmsProperties properties;

    @Autowired
    private RedisCache redisCache;

    /**
     * 验证码短信模版ID
     */
    @Value("${sms.sms-code}")
    private String templateCode;

    /**
     * 发送短信
     *
     * @param templateCode 短信模版ID
     * @param phone        电话号码
     * @param content      短信内容 JSON字符串
     */
    public boolean sendSms(String templateCode, String phone, String content) {

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", properties.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", properties.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", content);


        try {

            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            JSONObject jsonObject = new JSONObject(data);
            boolean code = "OK".equals(jsonObject.getString("Code"));
            if (!code) {
                log.error(jsonObject.getString("Message"));
            }
            return code;

        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 发送短信验证码
     * @param phone 电话号码
     * @param code 验证码
     * @return 发送结果
     */
    public boolean sendSmsCode(String phone, String code) {
        return this.sendSms(templateCode, phone, "{code:'" + code + "'}");
    }

    /**
     * 校验手机号验证码是否正确
     * @param phone
     * @param code
     * @return
     */
    public boolean verifyCode(String phone, String code){
        String result=redisCache.getCacheObject(Constant.SMS_KEY+phone);
        if (StringUtil.isEmpty(result)){
            return false;
        }
        if (result.equals(code)){
            return true;
        }
        return false;
    }

}
